<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  canvas {
    border: 1px solid #ccc;

  }
</style>
<canvas id="canvas" width="500" height="500"></canvas>
<!-- 顶点着色器 -->
<script id="vertex-shader" type="x-shader/x-vertex">
  attribute vec2 aPosition;
  attribute vec4 aColor;
  varying vec4 vColor;
 
   void main(){
    gl_PointSize = 10.0;
    gl_Position = vec4(aPosition,0.0,1.0);  
    vColor = aColor;
   }
</script>
<!-- 片段着色器 -->
<script id="fragment-shader" type="x-shader/x-fragment">
  precision highp float;
  varying vec4 vColor;

  void main(){
    gl_FragColor = vColor;
  }
</script>
<script>
  const canvas = document.getElementById('canvas')
  const gl = canvas.getContext('webgl');
  //创建顶点/片元着色器
  const vertexShader = gl.createShader(gl.VERTEX_SHADER);
  const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  //获取顶点/片元源码
  const vertextSource = document.getElementById('vertex-shader').innerText;
  const fragementSource = document.getElementById('fragment-shader').innerText;
  //着色器绑定源码
  gl.shaderSource(vertexShader, vertextSource);
  gl.shaderSource(fragmentShader, fragementSource);
  //编译着色器
  gl.compileShader(vertexShader);
  gl.compileShader(fragmentShader);
  //创建着色器程序
  const program = gl.createProgram();
  //程序绑定着色器
  gl.attachShader(program, vertexShader);
  gl.attachShader(program, fragmentShader);
  //连接程序对象
  gl.linkProgram(program);
  gl.useProgram(program);

  const vertices = new Float32Array([
    -0.5,
    0.5, //第一个点xy轴坐标
    0.5,
    -0.5,    //第二个点xy轴坐标
  ]);

  const colors = new Float32Array([
    0.0, 0.0, 0.0, 1.0, //第一个点颜色
    1.0, 0.0, 0.0, 0.0, //第二个点颜色
  ])

  //创建缓冲区
  const buffer = gl.createBuffer();
  //绑定缓冲区
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  //获取顶点着色器变量
  const aPosition = gl.getAttribLocation(program, 'aPosition');
  gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 2 * Float32Array.BYTES_PER_ELEMENT, 0);
  gl.enableVertexAttribArray(aPosition);

  const colorLocation = gl.getAttribLocation(program, 'aColor');
  const colorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  gl.vertexAttribPointer(colorLocation, 4, gl.FLOAT, false, 4 * Float32Array.BYTES_PER_ELEMENT, 0)
  gl.enableVertexAttribArray(colorLocation)
  gl.drawArrays(gl.LINES, 0, 2);
</script>

<body>

</body>

</html>